#include<stdlib.h>
#include<stdio.h>
#include<iostream>
#include<unistd.h>
#include<assert.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<string.h>

using namespace std;

//子进程进行写入，父进程进行读取
int main()
{
    int fds[2];
    int n = pipe(fds);
    assert(n==0);

    pid_t id = fork();
    assert(id>=0);
    if(id==0)//子进程进行写入
    {
        close(fds[0]);//关闭读端

        const char* s = "我是子进程，我正在写入:";
        int cnt = 0;
        while(true)
        {
            char buffer[1024];
            snprintf(buffer,sizeof(buffer),"child say->%s[%d]->[%d]",s,getpid(),cnt++);
            write(fds[1],buffer,strlen(buffer));
            sleep(1);
        }
        //close(fds[1]);
        //cout<<"子进程关闭写端!\n";
        exit(0);
    }

    //父进程进行读取
    close(fds[1]);
    int c = 10;
    while(c--)
    {
        char buffer[1024];
        ssize_t s = read(fds[0],buffer,sizeof(buffer)-1);

        if(s>0)
        {
            buffer[s]  = 0;
            cout<<"patent get message#"<<buffer<<" my pid is :"<<getpid()<<endl;
        }
        else if(s==0)
        {
            cout<<"read over!\n";
            break;
        }

        //break;
    }
    close(fds[0]);
    cout<<"父进程关闭读端!\n";

    int status = 0;
    n = waitpid(id,&status,0);
    assert(n==id);

    cout<<"pid->"<<n<<":"<<(status&0x7f)<<endl;
    //读端关闭，会向子进程发送SIGPIPE信号，可能导致写端退出！
    return 0;
}